//K 个一组翻转链表
//测试链接 https://leetcode.cn/problems/reverse-nodes-in-k-group/
public class ReverseKGroup {
    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public ListNode reverseKGroup(ListNode head, int k) {
        //先求出需要逆序多少组
        int num = 0;
        ListNode cur = head;
        while (cur != null) {
            num++;
            cur = cur.next;
        }
        int count = num / k;

        ListNode ret = new ListNode(0);
        ListNode prev = ret;
        cur = head;

        while (count-- != 0) {
            ListNode temp = cur;
            for (int i = 0; i < k; i++) {
                ListNode next = cur.next;
                //头插
                cur.next = prev.next;
                prev.next = cur;
                cur = next;
            }
            prev = temp;
        }
        prev.next = cur;
        return ret.next;
    }
}
